<?php

class NCore_AtomDatasource implements NCore_IDatasource
{
    private $feed = NULL;
    private $limit = NULL;
    private $ds = NULL;
    private $name = NULL;

    function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function withFeed($feed)
    {
        $this->feed = $feed;
        return $this;
    }

    public function withLimit($limit)
    {
        if(!is_int($limit)) throw new Exception('The \'withinLimit\' method of the AtomDatasource only accepts integers.');

        $this->limit = $limit;
        return $this;
    }

    public function getDataset()
    {
        if(!is_null($this->ds)) return $this->ds;

        $ch = new NCore_CURL();

        $doc = new DOMDocument();
        $doc->loadXML($ch->getURLContents($this->feed));
        $this->ds = new NCore_Dataset();

        foreach ($doc->getElementsByTagName('entry') as $node)
        {
            if($this->limit > count($this->ds))
            {
                $entry = array (
                'title'     => trim($node->getElementsByTagName('title')->item(0)->nodeValue),
                'content'   => trim($node->getElementsByTagName('content')->item(0)->nodeValue),
                'link'      => trim($node->getElementsByTagName('link')->item(0)->getAttribute('href')),
                'updated'   => trim($node->getElementsByTagName('updated')->item(0)->nodeValue)
                );
                $this->ds[] = new NCore_Row($entry);
            }
            else
            {
                break;
            }
        }

        return $this->ds;
    }
}

?>